package com.hibernate.session;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
 * 使用getCurrentSession获取到的Session不用关闭		
 * @Description:
 * @Author: 刘兴
 * @Date : 2016年11月22日
 * @package : com.hibernate.session
 * @Java_Version : 1.7
 * @Version : 2016年11月22日上午9:31:43
 */
public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure("getCurrentSession.cfg.xml");

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}

	private void openSession() {
		//使用下面的方式获取的Session不用关闭，前提是设置了
		session = factory.getCurrentSession();
		transaction = session.beginTransaction();
	}

	private void closeSession() {
		transaction.commit();
	}

	@Test
	public void UserCurrentSession() {
		
		openSession();
		News news = new News("中央新闻", "刘兴", new Date());
		session.save(news);
		closeSession();
	}
	
}
